<template>
  <div class="rainfall">
    <TitleColumn name='实况降雨' >
      <a-button type="link" size="small" @click="handleMore" style="color: #5fa9eb">导出数据<DoubleRightOutlined /></a-button>
    </TitleColumn>
    <div class="content">
      <p class="info">{{state.hourRainData?.time}}（过去24小时）武穴市共有178个雨量站，其中<strong>{{state.hourRainData?.hasRain}}个</strong>雨量站监测有降雨，最大降雨测站为<strong>{{state.hourRainData?.maxStcd}}</strong>站点，降雨量<strong>{{state.hourRainData?.maxStcdData}}mm</strong>。</p>
      <ul class="list">
        <li
          v-for="(item, index) in rainLevels"
          :key="index"
          class="listItem"
          :class="{ active: selectedItem === index + 1 }"
          @click="handleItemClick(index + 1)"
        >
          <span>{{item.label}}</span>
          <strong>{{state.hourRainData?.[item.dataKey]}}</strong>
        </li>
      </ul>
    </div>
    <TableModal @register="registerModal"/>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref, watch } from 'vue';
import TitleColumn from '@/components/TitleColumn';
import { Icon } from '@gui-pkg/components';
import TableModal from './TableModal';
import { useModal } from "@gui-pkg/antdcomponents";
import { get24HourRainData } from '@/api/oneMap/baseData';
import {getGlobalMap} from "@/components/GlobalMap";
import {useAddTipsPoint} from "@/components/StationSearch/src/useAddTipsPoint";
import {message} from "ant-design-vue";
import selectedIcon from "@/assets/icon/A001.png";
import { DoubleRightOutlined } from '@ant-design/icons-vue';

defineOptions({ name: 'Rainfall' });

const [registerModal, { openModal: openModal }] = useModal();
const state = reactive({
  hourRainData: {
    time: '',
    hasRain: '',
    maxStcd: '',
    maxStcdData: '',
  }
});

// 当前选中的项目
const selectedItem = ref<number | null>(null);

// 雨量等级配置
const rainLevels = [
  { label: '0mm', dataKey: 'rain0' },
  { label: '0.1~10mm', dataKey: 'rain1' },
  { label: '10~25mm', dataKey: 'rain2' },
  { label: '25~50mm', dataKey: 'rain3' },
  { label: '50~100mm', dataKey: 'rain4' },
  { label: '100~250mm', dataKey: 'rain5' },
  { label: '＞250mm', dataKey: 'rain6' },
  { label: '设备离线', dataKey: 'nohasRain' },

];
const handleMore = () => {
  openModal(true, { record: 'val' });
}

// 监听选中状态变化
watch(selectedItem, (newVal, oldVal) => {
  console.log('选中状态变化:', oldVal, '->', newVal);

  if (newVal === null) {
    // 清除地图上的标记
    clearMapMarkers();
    emit('itemDeselected', { previousType: oldVal });
  }
});

// 清除地图标记
const clearMapMarkers = () => {
  const globalMap = getGlobalMap();
  const { removeLayer } = useAddTipsPoint(globalMap);
  removeLayer();
  console.log('已清除地图标记');
};

// 处理项目点击
const handleItemClick = (val: number) => {
  const globalMap = getGlobalMap();
  const { addTipsPoint, removeLayer, addTipsPointList } = useAddTipsPoint(globalMap);

  // 如果是点击已选中的项目，则取消选中
  if (selectedItem.value === val) {
    selectedItem.value = null;
    removeLayer();
    console.log('取消选中:', val);
    emit('itemDeselected', { type: val });
    return;
  }

  // 设置新的选中状态
  selectedItem.value = val;

  console.log('选中项目:', val);

  removeLayer();

  let data = [];
  if(val === 2){
    data = state.hourRainData.rain1List || [];
  } else if(val === 3){
    data = state.hourRainData.rain2List || [];
  } else if(val === 4){
    data = state.hourRainData.rain3List || [];
  } else if(val === 5){
    data = state.hourRainData.rain4List || [];
  } else if(val === 6){
    data = state.hourRainData.rain5List || [];
  } else if(val === 7){
    data = state.hourRainData.rain6List || [];
  } else if(val === 8){
    data = state.hourRainData.nohasRainList || [];
  } else if(val === 1){
    data = state.hourRainData.rain0List || [];
  }

  // 在地图上添加标记点
  for(let i = 0; i < data.length; i++){
    const pointInfo = {
      lgtd: data[i].lgtd,
      lttd: data[i].lttd,
      icon: selectedIcon,
      iconScale: 1,
      zoom: 14,
    };
    addTipsPointList(pointInfo);
  }

  // 如果有数据，将地图中心移动到第一个点
  if(data.length > 0){
    globalMap.getView().animate({
      center: [data[0].lgtd, data[0].lttd],
      duration: 1000,
      zoom: 12,
    });
  }

  // 触发自定义事件
  emit('itemSelected', {
    type: val,
    label: rainLevels[val - 1].label,
    count: state.hourRainData?.[rainLevels[val - 1].dataKey],
    data: data
  });
}

// 定义事件发射器
const emit = defineEmits(['itemSelected', 'itemDeselected']);

// 提供方法让父组件可以获取和设置选中状态
defineExpose({
  getSelectedItem: () => selectedItem.value,
  setSelectedItem: (val: number | null) => {
    if (val === null) {
      selectedItem.value = null;
    } else if (val >= 1 && val <= 8) {
      handleItemClick(val);
    }
  },
  clearSelection: () => {
    selectedItem.value = null;
  }
});

onMounted(async () => {
  const hourRainData = await get24HourRainData();
  state.hourRainData = hourRainData;
});
</script>

<style lang="less" rel="stylesheet/less" scoped>
.rainfall {
  width: 100%;
  ::v-deep(.titleIcon ) {
    width: 24px !important;
    height: 24px !important;
    background: url('@/assets/images/titleIcon1.png') no-repeat !important;
    background-size: contain !important;
  };
  .content {
    width: 100%;
    height: calc(100% - 40px);
    padding-top: 10px;
    display: flex;
    flex-direction: column;
    p.info {
      margin-bottom: 10px;
      line-height: 24px;
      strong {
        color: #0079FE;
      }
    }
    ul.list {
      width: 100%;
      display: grid;
      grid-template-columns: repeat(2, 48%);
      grid-template-rows: repeat(4, 30px);
      grid-gap: 10px;
      padding: 0 8px 0 4px;
      li.listItem {
        width: 100%;
        height: 30px;
        background: rgba(119, 165, 255, 0.15);
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 16px 0 18px;
        position: relative;
        cursor: pointer;
        transition: all 0.3s ease;
        border: 1px solid transparent;

        &::before {
          content: '';
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 4px;
          position: absolute;
          left: 6px;
          transition: all 0.3s ease;
        }

        span {
          color: #555;
          transition: color 0.3s ease;
        }

        strong {
          transition: color 0.3s ease;
        }

        &:hover {
          box-shadow: 0px 0px 6px 2px rgb(0 121 254 / 25%);
        }

        // 选中状态样式
        &.active {
          background: rgba(0, 121, 254, 0.2);
          border-color: #0079FE;
          box-shadow: 0px 0px 8px 3px rgb(0 121 254 / 35%);

          span, strong {
            color: #0079FE;
            font-weight: bold;
          }
        }
      }

      // 为每个项目设置不同的颜色
      li.listItem:nth-child(1) {
        &::before {
          background: #a7f08f;
        }
        &.active::before {
          background: #7ae056;
          box-shadow: 0 0 6px #a7f08f;
        }
      }
      li.listItem:nth-child(2) {
        &::before {
          background: #40d7ff;
        }
        &.active::before {
          background: #00c6ff;
          box-shadow: 0 0 6px #40d7ff;
        }
      }
      li.listItem:nth-child(3) {
        &::before {
          background: #1d81d6;
        }
        &.active::before {
          background: #0a6dc2;
          box-shadow: 0 0 6px #1d81d6;
        }
      }
      li.listItem:nth-child(4) {
        &::before {
          background: #5455fd;
        }
        &.active::before {
          background: #3435fd;
          box-shadow: 0 0 6px #5455fd;
        }
      }
      li.listItem:nth-child(5) {
        &::before {
          background: #bf5afc;
        }
        &.active::before {
          background: #b13afc;
          box-shadow: 0 0 6px #bf5afc;
        }
      }
      li.listItem:nth-child(6) {
        &::before {
          background: #f64242;
        }
        &.active::before {
          background: #f52222;
          box-shadow: 0 0 6px #f64242;
        }
      }
      li.listItem:nth-child(7) {
        &::before {
          background: #878889;
        }
        &.active::before {
          background: #6c6d6e;
          box-shadow: 0 0 6px #878889;
        }
      }
      li.listItem:nth-child(8) {
        &::before {
          background: #cccccc;
        }
        &.active::before {
          background: #b0b0b0;
          box-shadow: 0 0 6px #cccccc;
        }
      }
    }
  }
}
</style>
